<template>
  <div class="app-main-container">
    <QueryForm
      v-model="filters"
      :query-form-config="queryFormConfig"
      @handleQuery="getList(1)"
      @clear="clear"
    />
    <div class="doumee_table_header">
      <el-button
        v-preventReClick
        type="primary"
        @click="$router.push({ name: 'MerchantAdminEdit'})"
      >新增</el-button>
      <el-button
        v-preventReClick
        type="danger"
        :disabled="multipleSelection.length == 0"
        @click="delMerchant"
      >删除</el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      :header-row-class-name="'table-header'"
      class="doumee-element-table"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"
      />
      <el-table-column
        align="center"
        label="商户编码"
        prop="shopId"
        min-width="120"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="商户名称"
        prop="shopName"
        min-width="130"
        show-overflow-tooltip
      >
        <template v-slot="scope">
          <span class="primaryColor pointer" @click="handleDetail(scope.row)">{{
            scope.row.shopName
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="企业名称"
        prop="companyName"
        min-width="130"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="联系人"
        prop="userName"
        min-width="100"
      />
      <el-table-column
        align="center"
        label="联系电话"
        prop="userPhone"
        min-width="120"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="会员小程序"
        min-width="120"
        prop="appMemberStatus"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <span>{{ statusName(scope.row.appMemberStatus) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="运营小程序"
        prop="appOperationStatus"
        show-overflow-tooltip
        min-width="120"
      >
        <template slot-scope="scope">
          <span>{{ statusName(scope.row.appOperationStatus) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="省市区"
        prop="addr"
        min-width="150"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <span>{{ scope.row.proName || '' }}{{ scope.row.cityName || '' }}{{ scope.row.areaName || '' }}{{ scope.row.addr || '' }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="商务人员"
        prop="businessName"
        min-width="120"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="创建时间"
        prop="createTime"
        min-width="160"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="部署状态"
        prop="deployStatus"
        min-width="80"
        fixed="right"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <span>{{ scope.row.deployStatus == "1" ? "已部署" : "未部署" }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="状态"
        min-width="80"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.shopStatus"
            :active-value="'1'"
            :inactive-value="'0'"
            @change="upDateStatus(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        min-width="220"
        align="center"
        fixed="right"
      >
        <template slot-scope="scope">
          <div class="flex-cc">
            <el-button
              v-if="scope.row.deployStatus == '0'"
              type="text"
              @click="bsShow(scope.row)"
            >部署</el-button>
            <el-button
              v-if="scope.row.flag == '1'"
              v-preventReClick
              type="text"
              @click="zcShow(scope.row)"
            >代注册小程序</el-button>
            <el-button
              v-preventReClick
              type="text"
              @click="toEdit(scope.row)"
            >编辑</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <Paginations
      :total="totalCount"
      :page="pagination.page"
      @current-change="getList"
      @SizeChange="handleSizeChange"
    />
    <el-dialog
      title="商户部署"
      width="700px"
      :visible.sync="showBs"
      :close-on-click-modal="modalDialog"
      :close-on-press-escape="modalDialog"
    >
      <el-form ref="bsForm" class="doumee-form" :model="bsForm" label-width="120px" label-suffix="：" :rules="rules">
        <div class="warnningTip"><i class="el-icon-warning-outline" />请先联系项目经理/交付经理，创建商户数据库并提供商户库账号、密码</div>
        <el-form-item label="场馆名称" prop="venueName">
          <el-input v-model="bsForm.venueName" maxlength="50" placeholder="请输入场馆名称，不填写默认以商户名称作为场馆名称" clearable />
        </el-form-item>
        <el-form-item label="场馆ID" prop="venueId">
          <el-input v-model="bsForm.venueId" maxlength="20" placeholder="如果对接全民健身平台场馆，需要提供对应的场馆ID" clearable />
        </el-form-item>
        <el-form-item label="数据库链接" prop="dbUrl">
          <el-input v-model="bsForm.dbUrl" maxlength="200" placeholder="请输入数据库链接，包含端口和数据库名称" clearable />
        </el-form-item>
        <el-form-item label="数据库账号" prop="userName">
          <el-input v-model="bsForm.userName" maxlength="200" placeholder="请输入数据库账号" clearable />
        </el-form-item>
        <el-form-item label="数据库密码" prop="pwd">
          <el-input v-model="bsForm.pwd" maxlength="100" placeholder="请输入数据库密码" clearable />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showBs = false">取消</el-button>
        <el-button type="primary" :loading="bsLoading" @click="onSubmit('bsForm')">确认</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="代注册小程序"
      width="850px"
      :visible.sync="showZc"
      :close-on-click-modal="modalDialog"
      :close-on-press-escape="modalDialog"
    >
      <el-form ref="zcForm" class="doumee-form" :model="zcForm" label-width="9em" label-suffix="：" :rules="rules">
        <div class="warnningTip"><i class="el-icon-warning-outline" />代注册小程序需要以下资料：法人姓名、法人微信号、企业名称、统一信用代码，缺一不可。</div>
        <el-form-item label="法人姓名" prop="userName">
          <el-input v-model="zcForm.userName" maxlength="50" class="w400" placeholder="请输入法人姓名" clearable /><span class="tip-style">法人姓名与绑定微信银行卡的姓名一致</span>
        </el-form-item>
        <el-form-item label="法人微信号" prop="userWx">
          <el-input v-model="zcForm.userWx" maxlength="20" class="w400" placeholder="请输入法人微信号" clearable />
        </el-form-item>
        <el-form-item label="企业名称" prop="companyName">
          <el-input v-model="zcForm.companyName" maxlength="200" class="w400" placeholder="请输入企业名称" clearable /><span class="tip-style">企业名称需与工商部门登记信息一致</span>
        </el-form-item>
        <el-form-item label="统一信用代码" prop="companyCode">
          <el-input v-model="zcForm.companyCode" maxlength="200" class="w400" placeholder="请输入统一信用代码" clearable /><span class="tip-style">统一信用代码需与工商部门登记信息一致</span>
        </el-form-item>
        <el-form-item label="特殊资源" prop="type">
          <el-radio-group v-model="zcForm.type">
            <el-radio label="0">会员端</el-radio>
            <el-radio label="1">运营端</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showZc = false">取消</el-button>
        <el-button type="primary" :loading="zcLoading" @click="onSubmitb('zcForm')">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import QueryForm from '@/components/QueryForm'
import { queryFormConfig } from './config'
import { parseTime } from '@/utils'
import { shopList, addAgencyLogon, getShopBasicsInfo, shopDelete, deployDB, updateShopInfo } from '@/api'
import store from '@/store'
export default {
  name: 'MerchantAdmin',
  components: {
    QueryForm
  },
  data() {
    return {
      filters: {},
      multipleSelection: [],
      modalDialog: store.getters.dialog,
      pagination: {
        page: 1,
        rows: 10
      },
      showBs: false,
      showZc: false,
      queryFormConfig,
      meta: [],
      list: [],
      totalCount: 10,
      listLoading: false,
      bsForm: {},
      bsLoading: false,
      zcForm: {},
      zcLoading: false,
      rules: {
        dbUrl: [{ required: true, message: '请输入数据库链接，包含端口和数据库名称', trigger: 'blur' }],
        userName: [{ required: true, message: '请输入法人姓名', trigger: 'blur' }],
        userWx: [{ required: true, message: '请输入法人微信号', trigger: 'blur' }],
        companyName: [{ required: true, message: '请输入企业名称', trigger: 'blur' }],
        companyCode: [{ required: true, message: '请输入统一信用代码', trigger: 'blur' }],
        pwd: [{ required: true, message: '请输入数据库密码', trigger: 'blur' }],
        type: [{ required: true, message: '请选择小程序类型', trigger: 'change' }]

      }
    }
  },
  created() {
    this.meta = this.$route.meta.buttons || []
    this.getList(1)
  },
  activated() {
    if (this.$route.query.renovate) {
      this.getList(1)
    }
  },
  methods: {
    upDateStatus(row) {
      // 更新状态
      const arr = this.list
      const obj = { ...row }
      this.listLoading = true
      updateShopInfo({
        param: {
          id: obj.shopId,
          status: obj.shopStatus
        }
      })
        .then((res) => {
          this.listLoading = false
          if (res.errorCode === '000000') {
            if (obj.shopStatus === '1') {
              this.$message.success('启用成功')
            } else {
              this.$message.success('禁用成功')
            }
            this.getList(1)
          } else {
            arr.forEach((e) => {
              if (e.shopId === obj.shopId) {
                e.shopStatus = row.shopStatus === '1' ? '0' : '1'
              }
            })
            this.list = arr
          }
        })
        .catch(() => {
          this.listLoading = false
          arr.forEach((e) => {
            if (e.shopId === obj.shopId) {
              e.shopStatus = row.shopStatus === '1' ? '0' : '1'
            }
          })
          this.list = arr
        })
    },
    bsShow(e) {
      this.showBs = true
      this.bsForm = { shopId: e.shopId }
    },
    zcShow(e) {
      getShopBasicsInfo({
        param: { shopId: e.shopId }
      }).then((res) => {
        if (res.errorCode !== '000000') return
        const obj = res.record
        this.zcForm = {
          shopId: e.shopId,
          companyCode: obj.enterpriseCode,
          companyName: obj.enterpriseName,
          userName: obj.juridicalName,
          userWx: obj.juridicalWx,
          type: '0'
        }
        this.showZc = true
      })
    },
    onSubmitb(formName) {
      const that = this
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const param = { ...that.zcForm }
          that.zcLoading = true
          addAgencyLogon({ param })
            .then((res) => {
              that.zcLoading = false
              if (res.errorCode === '000000') {
                that.$message.success('注册成功')
                that.showZc = false
                that.getList(1)
              }
            })
            .catch((er) => {
              that.zcLoading = false
              console.log(er)
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    toEdit(e) {
      this.$router.push({ name: 'MerchantAdminEdit', query: { shopId: e.shopId }})
    },
    handleDetail(e) {
      this.$router.push({ name: 'MerchantAdminDetail', query: { shopId: e.shopId }})
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    onSubmit(formName) {
      const that = this
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const param = { ...that.bsForm }
          that.bsLoading = true
          deployDB({ param })
            .then((res) => {
              that.bsLoading = false
              if (res.errorCode === '000000') {
                that.$message.success('部署成功')
                that.showBs = false
                that.getList(1)
              }
            })
            .catch((er) => {
              that.bsLoading = false
              console.log(er)
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    statusName(status) {
      switch (status) {
        case '0': return '注册中'
        case '1': return '已绑定'
        case '2': return '已授权'
        case '3': return '注册失败'
        default: return '-'
      }
    },
    getList(page) {
      const { filters, pagination } = this
      if (page) {
        pagination.page = page
        this.pagination.page = Number(page)
        if (page === 1) {
          pagination.firstQueryTime = parseTime(new Date())
        }
      }
      this.listLoading = true
      shopList({
        pagination,
        param: {
          ...filters
        }
      })
        .then((res) => {
          this.listLoading = false
          if (res.errorCode === '000000') {
            this.list = res.recordList
            this.totalCount = res.totalCount
          }
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    delMerchant() {
      this.$confirm('此操作将删除选中商户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          shopDelete({ param: { shopIds: this.multipleSelection.map(e => e.shopId) }})
            .then(res => {
              if (res.errorCode !== '000000') return
              this.multipleSelection = []
              this.$message.success('删除成功')
              this.getList(1)
            })
        })
        .catch(() => {})
    },
    addMerchant() {},
    clear() {
      this.filters = {}
      this.getList(1)
    },
    handleSizeChange(value) {
      this.pagination.rows = value
      this.getList(1)
    }
  }
}
</script>

<style>

</style>
